<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-03-06
 * @Time: 09:58
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： AskMessage.php
 */
namespace app\api\model\ask;

use app\api\model\user\Users;
use think\Db;
use think\Log;
use think\Model;

class AskMessage extends Model {
    protected $table = 'ask_message';
    protected $pk = 'id';

    /**
     * messageSave
     * 保存留言到数据库
     *
     * @author zhengkai
     * @date 2018-03-06
     *
     * @param int $uid 用户id
     * @param int $askId 问答id
     * @param string $content 留言内容
     * @return bool
     */
    public static function messageSave($uid, $askId, $content)
    {
        Db::startTrans();
        try {
            self::create([
                'ask_id' => $askId,
                'user_id' =>  $uid,
                'content' => $content
            ]);

            // 更新问答留言统计数据
            $askMesageNum = Ask::getSingleField($askId, 'message_num');
            Db::table('ask')->where('ask_id', $askId)->update(['message_num' => ($askMesageNum+1)]);

            Db::commit();

            return true;
        } catch (\Exception $e) {
            Log::error('问答留言错误信息：'.$e->getMessage());

            Db::rollback();

            return false;
        }
    }

    /**
     * getAskMessage
     * 获取指定问答的留言数据
     *
     * @author zhengkai
     * @date 2018-03-06
     *
     * @param int $askId 问答id
     * @param int $page 当前页数，默认1
     * @param int $limit 每页加载数，默认10
     * @return false|static[]
     */
    public static function getAskMessage($askId, $page=1, $limit=10) {
        $data = self::all(function($query) use (&$askId, &$page, &$limit) {
            $query->where('ask_id', $askId)
                ->order('times desc')
                ->page($page, $limit);
        });

        foreach ($data as &$val) {
            $user = Users::getBaseInfo($val['user_id']);

            $val['user_nickname'] = $user['nickname'];
            $val['user_avatar'] = $user['avatar'];

            unset($val['ask_id'], $val['user_id']);
        }

        return $data;
    }
}